package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;

import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.MyZTextWatcher;
import com.sgb.capital.databinding.ActivityWithDrawBalanceBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.BindBankCardListEntity;
import com.sgb.capital.model.BusinessInfoByCompanyEntity;
import com.sgb.capital.utils.CryptoUtils;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.BalanceTimePop;
import com.sgb.capital.view.pop.NewWithdrawPop;
import com.sgb.capital.view.pop.SelectBankCardPopWindow;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.widget.MToast;
import com.sgb.capital.viewmodel.WithdrawalBalanceModel;

import java.util.List;
import java.util.Map;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

/**
 * 作者:张磊
 * 日期:2021/11/11 0016
 * 说明:余额提现
 */
public class WithdrawalBalanceActivity extends BaseActivity {
    WithdrawalBalanceModel mModel;
    private ActivityWithDrawBalanceBinding mBinding;
    private SelectBankCardPopWindow mCardPopWindow;
    private List<BindBankCardListEntity> cardList;
    private float mBalance;
    private BindBankCardListEntity mEntity;
    private boolean mIsUser;
    BalanceTimePop balanceTimePop;
    int FailCount = 1;
    private BusinessInfoByCompanyEntity mCompanyEntity;
    private String mUsableBalance;
    private NewWithdrawPop mNewWithdrawPop;
    private String mBankAccount;

    public static void start(Context context, boolean isUser) {
        Intent intent = new Intent();
        intent.setClass(context, WithdrawalBalanceActivity.class);
        intent.putExtra("isUser", isUser);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(WithdrawalBalanceActivity.this, R.layout.activity_with_draw_balance);
        mModel = new ViewModelProvider(this).get(WithdrawalBalanceModel.class);
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.bankCard.setOnClickListener(v -> showPop());
        mBinding.accountingDate.setOnClickListener(v -> balanceTimePop.showPopupWindow());
        mCardPopWindow = new SelectBankCardPopWindow(WithdrawalBalanceActivity.this);
        mCardPopWindow.setBgView(mBinding.grayLayout);
        Utils.setStatusBarLightMode(this, true);
        mNewWithdrawPop = new NewWithdrawPop(this, new NewWithdrawPop.DialogButtonListener() {
            @Override
            public void applyCode(String phone) {
                mModel.applyCode(WithdrawalBalanceActivity.this, phone);
            }

            @Override
            public void applyWithdrawal(Map map) {
                mModel.apply(WithdrawalBalanceActivity.this, map);
            }
        });
    }

    public void initData() {
        //处理余额数据
        mIsUser = getIntent().getBooleanExtra("isUser", false);
        if (mIsUser) {
            mModel.getPersonBalance(this);
            mBinding.accountingDate.setVisibility(View.GONE);
            mBinding.WithdrawalTv.setText("提现手续费：￥0.40");
        } else {
            mModel.getCompanyBalance(this);
            mBinding.accountingDate.setVisibility(View.VISIBLE);
            mBinding.WithdrawalTv.setText("提现手续费：￥2.00");
        }
        mModel.getBindBankCardList(this);
        balanceTimePop = new BalanceTimePop(this);
    }

    public void initListener() {
        // 提现
        mBinding.tvApplyWithdrawal.setOnClickListener(v -> showDialog());
        mBinding.allBalance.setOnClickListener(v -> {
            mBinding.inputMoney.setText(mUsableBalance);
            mBinding.inputMoney.requestFocus();
            mBinding.inputMoney.setSelection(mBinding.inputMoney.getText().toString().length());
        });
        mCardPopWindow.setOnResultClick((key1, key2, key3) -> {
            if (key1 == null) return;
            mEntity = (BindBankCardListEntity) key1;
            // TODO: 2021/6/16 0016 解密
            mBankAccount = CryptoUtils.decryptAES_ECB(mEntity.bankAccount);
            mBinding.bankCard.setText(mEntity.bankName + "(" + mBankAccount.substring(0, 4) + " **** **** " + mBankAccount.substring(mBankAccount.length() - 4) + ")");
        });
        mBinding.inputMoney.addTextChangedListener(new MyZTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Utils.input2(s, mBinding.inputMoney, 0, "输入错误");
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    mBinding.WithdrawalTv.setVisibility(View.GONE);
                } else {
                    try {
                        float num = Float.parseFloat(s.toString());
                        if (num > Float.parseFloat(mUsableBalance)) {
                            mBinding.allBalance.setVisibility(View.GONE);
                            mBinding.WithdrawalTv.setVisibility(View.VISIBLE);
                            mBinding.accountBalance.setTextColor(Utils.getColor(R.color.color_FF2928));
                            mBinding.accountBalance.setText("当前最高可提现金额为" + mUsableBalance + "元");
                            mBinding.tvApplyWithdrawal.setEnabled(false);
                        } else if (num == 0) {
                            mBinding.allBalance.setVisibility(View.GONE);
                            mBinding.accountBalance.setTextColor(Utils.getColor(R.color.color_FF2928));
                            mBinding.accountBalance.setText("申请提现金额不可为0");
                            mBinding.tvApplyWithdrawal.setEnabled(false);
                        } else {
                            mBinding.allBalance.setVisibility(View.VISIBLE);
                            mBinding.WithdrawalTv.setVisibility(View.VISIBLE);
                            mBinding.accountBalance.setText("账户余额为" + mBalance + "元，");
                            mBinding.accountBalance.setTextColor(Utils.getColor(R.color.color_666666));
                            mBinding.tvApplyWithdrawal.setEnabled(true);
                        }
                    } catch (Exception e) {

                    }
                }
            }
        });
    }

    private void showPop() {
        mCardPopWindow.showDownPopwindow(mBinding.grayLayout, true);
    }

    private void showDialog() {
        // TODO: 2021/11/10 0010
        if (mEntity == null) return;
        if (TextUtils.isEmpty(mBinding.inputMoney.getText().toString())) {
            MToast.showToast(mContext, "请输入提现金额");
            return;
        }
        // TODO: 2021/6/16 0016 解密
        String mobileId = CryptoUtils.decryptAES_ECB(mEntity.mobileId);
        mNewWithdrawPop.setData(mEntity.pagreementId, mBankAccount, mEntity.bankName, mBinding.inputMoney.getText().toString(), mobileId, mIsUser);
        mModel.applyCode(this, mobileId);
    }

    private void setBalance(BusinessInfoByCompanyEntity entity) {
        mBalance = entity.balance;// 余额
        mCompanyEntity = entity;
        mUsableBalance = Utils.getDecimalFormat(mBalance - mCompanyEntity.todayOrderAmount);
        mBinding.accountBalance.setText("账户余额为" + mBalance + "元，");
        // TODO: 2021/7/3 0003
        mBinding.tipTv.setText("(其中包含当日下单签收解冻金额和充值金额 ¥" + entity.todayOrderAmount + ")，需T+1才可提现");
        if (mBalance == 0) {
            mBinding.tvApplyWithdrawal.setEnabled(false);
        } else {
            mBinding.tvApplyWithdrawal.setEnabled(true);
        }
    }

    private void setCardList(List<BindBankCardListEntity> entities) {
        cardList = entities;
        if (entities == null || entities.size() == 0) return;
        mEntity = entities.get(0);
        mCardPopWindow.setData(cardList);
        mCardPopWindow.setDefData(0);
        // TODO: 2021/6/16 0016 解密
        mBankAccount = CryptoUtils.decryptAES_ECB(mEntity.bankAccount);
        mBinding.bankCard.setText(mEntity.bankName + "(" + mBankAccount.substring(0, 4) + " **** **** " + mBankAccount.substring(mBankAccount.length() - 4) + ")");
    }

    private void applyWithdrawal(Bean bean) {
        if (bean.type == 1) {
            //TODO 提现成功跳转提现详情
            mNewWithdrawPop.dismiss();
            // pop.clearData();
            WithdrawalDetailActivity.start(this, bean.url);
        } else if (2 == bean.type) {
            //TODO 验证码错误
            if ("E00000".equals(bean.url) && FailCount < 3) {
                FailCount++;
                mNewWithdrawPop.mTvTip.setTextColor(Utils.getColor(R.color.color_FF2928));
                mNewWithdrawPop.mTvTip.setText("验证码错误");
                mNewWithdrawPop.mTvTip.setVisibility(View.VISIBLE);
            } else {
                FailCount = 1;
                mNewWithdrawPop.dismiss();
                new TipPop(mContext, "", "提现申请失败，请重新尝试", "", "知道了").show();
            }
        }
    }

    @Override
    public void initObserve() {
        mModel.mBankCardListEntityMutableLiveData.observe(this, bindBankCardListEntities -> setCardList(bindBankCardListEntities));
        mModel.applyWithdrawal.observe(this, withdrawal -> applyWithdrawal(withdrawal));
        mModel.mApplyCode.observe(this, code -> {
            mNewWithdrawPop.show();
            mNewWithdrawPop.setStartTimer();
        });
        mModel.mBalance.observe(this, balance -> setBalance(balance));
    }

    @Override
    protected void onDestroy() {
        Utils.sendMsg(Constants.EVENT_REFRESH, null);
        super.onDestroy();
    }
}
